<template>
  <CommonPage :show-header="false">
    <n-space>
      <n-button type="primary" @click="showModal = true"> 修改密码 </n-button>
    </n-space>
    <n-form ref="formRef" :model="user" label-placement="top" mt-20>
      <n-grid :cols="24" :x-gap="24">
        <n-form-item-gi :span="12" label="用户名">
          <n-input v-model:value="user.username"></n-input>
        </n-form-item-gi>
        <n-form-item-gi :span="12" label="昵称">
          <n-input v-model:value="user.nickname"></n-input>
        </n-form-item-gi>
        <n-form-item-gi :span="12" label="头像">
          <n-input v-model:value="user.avatar"></n-input>
        </n-form-item-gi>
        <n-form-item-gi :span="12" label="邮箱">
          <n-input v-model:value="user.email"></n-input>
        </n-form-item-gi>
      </n-grid>
    </n-form>
    <n-space style="display: flex; justify-content: flex-end">
      <n-button type="primary" @click="saveData">
        <TheIcon v-if="!btnLoading" icon="line-md:confirm-circle" class="mr-5" :size="18" /> 保存
      </n-button>
    </n-space>

    <n-modal v-model:show="showModal">
      <n-card style="width: 600px" :bordered="false" size="huge" role="dialog" aria-modal="true">
        <n-form ref="formRef" :model="modelRef" :rules="rules">
          <n-form-item path="password" label="密码">
            <n-input
              v-model:value="modelRef.password"
              type="password"
              @input="handlePasswordInput"
              @keydown.enter.prevent
            />
          </n-form-item>
          <n-form-item ref="rPasswordFormItemRef" first path="reenteredPassword" label="重复密码">
            <n-input
              v-model:value="modelRef.reenteredPassword"
              :disabled="!modelRef.password"
              type="password"
              @keydown.enter.prevent
            />
          </n-form-item>
        </n-form>
        <template #footer>
          <footer flex justify-end>
            <slot name="footer">
              <n-button @click="showModal = false">取消</n-button>
              <n-button :loading="btnLoading" ml-20 type="primary" @click="handleValidateButtonClick"
                >修改密码</n-button
              >
            </slot>
          </footer>
        </template>
      </n-card>
    </n-modal>
  </CommonPage>
</template>

<script setup>
import { updateUser, getUser, updateUserPassword } from '@/api/system/user.js'
import CommonPage from '@/components/page/CommonPage.vue'
import { useMessage } from 'naive-ui'
import { useUserStore } from '@/store'
import api from '@/api/index.js'

const user = ref({})
const userStore = useUserStore()
const formRef = ref(null)
const rPasswordFormItemRef = ref(null)
const message = useMessage()
const showModal = ref(false)
const modelRef = ref({
  password: null,
  reenteredPassword: null,
})

const btnLoading = ref(false)

defineOptions({ name: 'User' })

onActivated(() => {
  console.log('onActivated')
  getData()
})

function getData() {
  getUser().then((res) => {
    user.value = res.data
  })
}

function saveData() {
  $message.loading('loading...')
  const res = updateUser(user.value)
  $message.success('保存成功')
}

function validatePasswordStartWith(rule, value) {
  return (
    !!modelRef.value.password &&
    modelRef.value.password.startsWith(value) &&
    modelRef.value.password.length >= value.length
  )
}
function validatePasswordSame(rule, value) {
  return value === modelRef.value.password
}
const rules = {
  password: [
    {
      required: true,
      message: '请输入密码',
    },
  ],
  reenteredPassword: [
    {
      required: true,
      message: '请再次输入密码',
      trigger: ['input', 'blur'],
    },
    {
      validator: validatePasswordStartWith,
      message: '两次密码输入不一致',
      trigger: 'input',
    },
    {
      validator: validatePasswordSame,
      message: '两次密码输入不一致',
      trigger: ['blur', 'password-input'],
    },
  ],
}

function handlePasswordInput() {
  if (modelRef.value.reenteredPassword) {
    rPasswordFormItemRef.value?.validate({ trigger: 'password-input' })
  }
}

function handleValidateButtonClick(e) {
  e.preventDefault()
  formRef.value?.validate((errors) => {
    if (!errors) {
      console.log(user.value.username)
      updateUserPassword(user.value.username, modelRef.value.password)
      message.success('密码修改成功，请重新登陆')
      showModal.value = false
      logout()
    } else {
      console.log(errors)
      message.error('保存失败')
    }
  })
}

async function logout() {
  try {
    await api.logout()
    userStore.logout()
  } catch (error) {
    console.error(error)
    $message.removeMessage()
  }
}
</script>

<style scoped>
.card-tabs .n-tabs-nav--bar-type {
  padding-left: 4px;
}
</style>
